package com.kotlinx.view.selectDialog

import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.view.View
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlinx.view.R
import com.kotlinx.view.base.YBaseDialog
import com.kotlinx.view.color.ViewColor
import com.kotlinx.view.databinding.YDialogBinding
import com.kotlinx.view.databinding.YDialogRecyclerviewBinding
import com.kotlinx.view.databinding.YDialogRecyclerviewItemBinding
import com.kotlinx.view.utils.YDrawableUtils

/**
 * 单选多选弹窗
 * @author yujing 2023年8月17日16:37:48
 */
/*
用法：
//单选
val list = arrayListOf("单项选择————001", "单项选择————002", "单项选择————003", "单项选择————004", "单项选择————005")
val dialog = YViewSelectDialog(this, list.size, "请选择一个选项").apply {
    cancel = true
    viewSizeScale = 1.0f
    btNameOK = "确定"
    btNameCancel = "取消"
    itemName = { position ->
        val item = list[position]
        "${item}"
    }
    okListener = { position ->
        if (position != -1) {
            val item = list[position]
            YToast.show("选择了: ${item}")
        }
        dismiss()
    }
    show()
}

//单选选中行改变颜色
val list = arrayListOf("单项选择————001内容很长内容", "单项选择————002", "单项选择————003", "单项选择————004", "单项选择————005", "单项选择————006", "单项选择————007", "单项选择————008")
YViewSelectDialog(this, list.size, "请选择一个选项").apply {
    //不显示取消按钮
    cancel = true
    //不显示单选按钮
    isShowRadioButton = false
    //单击回调监听
    itemClickListener = { binding, position ->
        //清空颜色
        viewColor.itemContentTextColors = ArrayList()
        //清空颜色
        viewColor.itemBackgroundColors = ArrayList()
        //修改选中行颜色
        for (value in checkList) {
            viewColor.itemContentTextColors.add(if (value.isCheck) "#22FF22".toColorInt() else "#222222".toColorInt())
            viewColor.itemBackgroundColors.add(if (value.isCheck) "#20004400".toColorInt() else "#FFFFFF".toColorInt())
        }
    }
    //每行文字默认颜色
    viewColor.itemContentTextColors = arrayListOf(
        "#222222".toColorInt()
    )
    //每行默认背景颜色
    viewColor.itemBackgroundColors = arrayListOf(
        "#FFFFFF".toColorInt()
    )
    itemName = { position -> list[position] }
    okListener = { position ->
        if (position != -1) {
            val item = list[position]
            YToast.show("选择了: ${item}")
        }
        dismiss()
    }
    show()
}

//多选
val list = arrayListOf("多项选择————001", "多项选择————002", "多项选择————003", "多项选择————004", "多项选择————005")
val dialog = YViewSelectDialog(this, list.size, "请选择多个选项").apply {
    cancel = true
    viewSizeScale = 1.0f
    btNameOK = "确定"
    btNameCancel = "取消"
    checkBoxType = 2
    defaultLinear = {
        it == 1 || it == 3
    }
    itemName = { position ->
        val item = list[position]
        "${item}"
    }
    okListener = { position ->
        val finishList = arrayListOf("")
        for (i in 0 until checkList.size) {
            if (checkList[i].isCheck) finishList.add(list[i])
        }
        YToast.show("选择了: ${listToString(finishList)}")
        dismiss()
    }
    cancelListener = {
        dismiss()
    }
    show()
}


//单选，直接选择
val list = arrayListOf("单项选择————001", "单项选择————002", "单项选择————003", "单项选择————004", "单项选择————005", "单项选择————006", "单项选择————007", "单项选择————008", "单项选择————009")
val dialog = YViewSelectDialog(this, list.size, "请选择一个选项").apply {
    isSingleSelect = true
    cancel = true
    itemName = { position -> list[position] }
    okListener = { position ->
        if (position != -1) {
            val item = list[position]
            YToast.show("选择了: ${item}")
        }
        dismiss()
    }
    show()
}
 */


/*
//修改颜色1
val list = arrayListOf("单项选择————001", "单项选择————002", "单项选择————003", "单项选择————004", "单项选择————005")
val dialog = YViewSelectDialog(this, list.size, "请选择一个选项").apply {
    cancel = true
    viewColor.itemContentTextColors = arrayListOf(
        Color.parseColor("#773355"),
        Color.parseColor("#337755"),
        Color.parseColor("#335577"),
        Color.parseColor("#775533"),
        Color.parseColor("#557733"),
        Color.parseColor("#553377")
    )
    itemName = { position -> list[position] }
    okListener = { position ->
        if (position != -1) {
            val item = list[position]
            YToast.show("选择了: ${item}")
        }
        dismiss()
    }
    show()
}

//修改颜色2"
val strings = arrayListOf(
    "您好，请查看小程序首页，了解更多详细",
    "单项选择1",
    "单项选择2",
    "单项选择3",
    "单项选择4，非常多内容，非常多内容，非常多内容，非常多内容，非常多内容，非常多内容",
    "单项选择5"
)
val colors = arrayListOf("#773355", "#337755", "#FF0000", "#00ff00", "#335577", "#775533", "#557733", "#553377")
val list = arrayListOf<CharSequence>()
for (i in strings.indices) {
    list.add(buildSpannedString {
        scale(0.7F) {
            color(Color.parseColor(colors[i % colors.size])) {
                append(strings[i])
            }
        }
    })
}
val dialog = YViewSelectDialog(this, list.size, "请选择一个选项").apply {
    cancel = true
    itemName = { position -> list[position] }
    okListener = { position ->
        if (position != -1) {
            val item = list[position]
            YToast.show("选择了: ${item}")
        }
        dismiss()
    }
    show()
}
 */
class YViewSelectDialog(activity: Activity, var size: Int, var titleText: CharSequence? = null) : YBaseDialog<YDialogBinding>(activity, R.layout.y_dialog, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar) {
    //当前项：名称
    var itemName: ((position: Int) -> CharSequence)? = null

    //当前项：是否选中
    var defaultLinear: ((position: Int) -> Boolean)? = null

    //确定按钮
    var okListener: ((position: Int) -> Unit)? = null

    //取消按钮
    var cancelListener: (() -> Unit)? = null

    var btNameOK: CharSequence = "确　定"

    var btNameCancel: CharSequence = "取　消"

    //文字大小比例
    var viewSizeScale: Float

    //颜色
    var viewColor: ViewColor

    //初始化完成
    var initCompleteListener: ((YDialogBinding) -> Unit)? = null

    //adapter
    var adapter: BaseAdapter<Check>? = null

    //单选 复选
    var checkBoxType = 1 //1 单选  2 复选

    //如果是单选模式,点击可以直接选中，并返回
    var isSingleSelect = false

    //是否显示（单选模式才生效）
    var isShowRadioButton = true

    //弹窗中心view
    lateinit var contentBinding: YDialogRecyclerviewBinding

    //每个item渲染回调
    var itemBindingListener: ((binding: YDialogRecyclerviewItemBinding, position: Int) -> Unit)? = null

    //每个item点击
    var itemClickListener: ((binding: YDialogRecyclerviewItemBinding, position: Int) -> Unit)? = null
    init {
        this.viewColor = ViewColor(activity)
        viewColor.contentBackgroundColor = Color.parseColor("#F8F8F8")
        val width = Resources.getSystem().displayMetrics.widthPixels
        val height = Resources.getSystem().displayMetrics.heightPixels
        //如果是竖屏
        if (height > width) {
            heightPixels = 0.5f //高
            viewSizeScale = 1.25f
        } else {
            heightPixels = 0.7f //高
            viewSizeScale = 1f
        }
        //初始view
        initContentView()
    }

    class Check {
        var isCheck = false
        override fun toString(): String {
            return "$isCheck"
        }
    }

    //选择
    val checkList: MutableList<Check> = arrayListOf()

    override fun initBefore() {
        fillColor = viewColor.fillBackgroundColor //整体填充颜色
        strokeColor = viewColor.fillStrokeColor  //整体边框颜色
    }

    //初始化中心view
    private fun initContentView() {
        contentBinding = DataBindingUtil.bind(View.inflate(activity, R.layout.y_dialog_recyclerview, null))!!
    }

    override fun init() {
        //设置标题
        binding.tvTitle.text = titleText
        binding.llContent.removeAllViews()
        binding.llContent.setPadding(dp2px(10F))
        binding.llContent.addView(contentBinding.root)

        initRecyclerView(contentBinding.rvContent)
        //设置确定按钮
        binding.btOk.text = btNameOK
        binding.btOk.setOnClickListener {
            var position = -1 //如果是单选，返回选择项目
            var checkCount = 0
            for (i in 0 until checkList.size) {
                if (checkList[i].isCheck) {
                    checkCount++
                    position = i
                }
            }
            //如果选项不是1个
            if (checkCount != 1) {
                position = -1
            }
            okListener?.invoke(position)
        }
        //设置取消按钮
        binding.btCancel.text = btNameCancel
        binding.btCancel.setOnClickListener {
            cancelListener?.invoke()
        }

        //---------------------------设置显示 开始---------------------------
        binding.run {
            if (titleText == null) {
                llTitle.visibility = View.GONE
                ivTitleDivider.visibility = View.GONE
            }

            if (okListener == null) {
                btOk.visibility = View.GONE
                ivButtonDivider.visibility = View.GONE
            }

            if (cancelListener == null) {
                btCancel.visibility = View.GONE
                ivButtonDivider.visibility = View.GONE
            }

            if (okListener == null && cancelListener == null) {
                llBt.visibility = View.GONE
                ivContentDivider.visibility = View.GONE
            }

            //如果是直接选中，不显示按钮
            if (isSingleSelect) {
                llBt.visibility = View.GONE
            }
        }
        //---------------------------设置显示 结束---------------------------

        //---------------------------缩放 开始---------------------------
        if (viewSizeScale != 1.0f) {
            binding.run {
                //设置文字放大缩小倍数
                tvTitle.textSize = px2sp(tvTitle.textSize.toInt()) * viewSizeScale
                btCancel.textSize = px2sp(btCancel.textSize.toInt()) * viewSizeScale
                btOk.textSize = px2sp(btOk.textSize.toInt()) * viewSizeScale

                //标题高度
                val lpTitle = llTitle.layoutParams as LinearLayout.LayoutParams
                lpTitle.height = (lpTitle.height * viewSizeScale).toInt()
                llTitle.layoutParams = lpTitle

                //按钮高度缩放
                val lp = llBt.layoutParams as LinearLayout.LayoutParams
                lp.height = (lp.height * viewSizeScale).toInt()
                llBt.layoutParams = lp
            }
        }
        //---------------------------缩放 结束---------------------------


        //---------------------------设置颜色 开始---------------------------
        binding.llTitle.setBackgroundColor(viewColor.titleBackgroundColor)
        binding.tvTitle.setTextColor(viewColor.titleTextColor)
        binding.ivTitleDivider.setBackgroundColor(viewColor.titleDividerColor)

        binding.llContent.setBackgroundColor(viewColor.contentBackgroundColor)
        binding.ivContentDivider.setBackgroundColor(viewColor.contentDividerColor)

        binding.btCancel.setTextColor(viewColor.buttonCancelTextColor)
        binding.btOk.setTextColor(viewColor.buttonOkTextColor)
        binding.ivButtonDivider.setBackgroundColor(viewColor.buttonDividerColor)


        val focusedDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.focusedTrueButtonOkColor, 0, Color.WHITE, 0F, 0F, 0F, 0F)
        val pressedDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.pressedTrueButtonOkColor, 0, Color.WHITE, 0F, 0F, 0F, 0F)
        val normalDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.pressedFalseButtonOkColor, 0, Color.WHITE, 0F, 0F, 0F, 0F)
        binding.btOk.background = YDrawableUtils.createStateListDrawable(focusedDrawableOk, pressedDrawableOk, normalDrawableOk)


        val focusedDrawableCancel = YDrawableUtils.createGradientDrawable(viewColor.focusedTrueButtonCancelColor, 0, Color.WHITE, 0F, 0F, 0F, 0F)
        val pressedDrawableCancel = YDrawableUtils.createGradientDrawable(viewColor.pressedTrueButtonCancelColor, 0, Color.WHITE, 0F, 0F, 0F, 0F)
        val normalDrawableCancel = YDrawableUtils.createGradientDrawable(viewColor.pressedFalseButtonCancelColor, 0, Color.WHITE, 0F, 0F, 0F, 0F)
        binding.btCancel.background = YDrawableUtils.createStateListDrawable(focusedDrawableCancel, pressedDrawableCancel, normalDrawableCancel)
        //---------------------------设置颜色 结束---------------------------

        //初始化完成
        initCompleteListener?.invoke(binding)
    }


    /**
     * 设置RecyclerView
     */
    private fun initRecyclerView(rv: RecyclerView) {
        checkList.clear()
        for (i in 0 until size) {
            checkList.add(Check().apply {
                isCheck = if (defaultLinear == null) {
                    false //不选中
                } else defaultLinear!!.invoke(i) //根据返回值选中
            })
        }
        rv.init()
        adapter = object : BaseAdapter<Check>(R.layout.y_dialog_recyclerview_item, checkList) {

            override fun item(holder: BaseHolder, position: Int) {
                holder.setIsRecyclable(false)//不缓存不复用

                val binding = holder.binding as YDialogRecyclerviewItemBinding
                val item = checkList[position]

                binding.tv.setTextColor(viewColor.itemContentTextColors[position % viewColor.itemContentTextColors.size])
                binding.tv.text = itemName?.invoke(position)

                //如果是单选
                if (checkBoxType == 1) {
                    binding.rb.isVisible = true
                    binding.cb.isVisible = false
                    binding.rb.isClickable = false
                    binding.rb.isChecked = item.isCheck
                } else {
                    binding.rb.isVisible = false
                    binding.cb.isVisible = true
                    binding.cb.isClickable = false
                    binding.cb.isChecked = item.isCheck
                }

                //默认显示单选按钮，如果false，就不显示单选按钮
                if (!isShowRadioButton) {
                    binding.rb.isVisible = false
                    binding.rb.isClickable = false
                }

                val focusedDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.itemBackgroundColors[position % viewColor.itemBackgroundColors.size], 0, Color.WHITE, 0F, 0F, 0F, 0F)
                val pressedDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.itemBackgroundPressColors[position % viewColor.itemBackgroundPressColors.size], 0, Color.WHITE, 0F, 0F, 0F, 0F)
                val normalDrawableOk = YDrawableUtils.createGradientDrawable(viewColor.itemBackgroundColors[position % viewColor.itemBackgroundColors.size], 0, Color.WHITE, 0F, 0F, 0F, 0F)
                binding.itemContent.background = YDrawableUtils.createStateListDrawable(focusedDrawableOk, pressedDrawableOk, normalDrawableOk)

                binding.itemContent.setOnClickListener {
                    if (isSingleSelect) {
                        okListener?.invoke(position)
                    } else {
                        val item = checkList[position]
                        //如果是单选
                        if (checkBoxType == 1) {
                            for (i in checkList) i.isCheck = false
                            item.isCheck = true
                        } else {
                            item.isCheck = !item.isCheck
                        }
                        itemClickListener?.invoke(binding, position)
                        adapter?.notifyDataSetChanged()
                    }
                }
                itemBindingListener?.invoke(binding, position)
            }
        }
        adapter?.onCreateViewHolderListener = {
            val binding = it.binding as YDialogRecyclerviewItemBinding
            //---------------------------缩放 开始---------------------------
            //设置文字放大缩小倍数
            binding.tv.textSize = px2sp(binding.tv.textSize.toInt()) * viewSizeScale
            //---------------------------缩放 结束---------------------------

            //---------------------------设置颜色 开始---------------------------
            binding.tv.setTextColor(viewColor.contentTextColor)
            //---------------------------设置颜色 结束---------------------------
        }
        rv.adapter = adapter
    }

    private fun RecyclerView.init(orientation: Int = RecyclerView.VERTICAL, items: Int? = null): RecyclerView {
        //单行/单列
        if (items == null) {
            val layoutManager = LinearLayoutManager(context)
            layoutManager.isSmoothScrollbarEnabled = true
            layoutManager.orientation = orientation
            this.layoutManager = layoutManager
            return this
        }
        //多行多列
        val layoutManager = GridLayoutManager(context, items)
        layoutManager.isSmoothScrollbarEnabled = true
        layoutManager.orientation = orientation
        this.layoutManager = layoutManager
        return this
    }
}